package com.example.aigc_education.config;


import com.example.aigc_education.utils.StringUtils;
import com.example.aigc_education.ws.AiTeacherWSHandler;
import com.example.aigc_education.ws.PlusWebSocketHandler;
import com.example.aigc_education.ws.PlusWebSocketInterceptor;
import com.example.aigc_education.ws.SecurityHandshakeHandler;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Data
@EnableWebSocket
@Configuration
public class WebSocketConfig {

    @Value("${ws.enabled}")
    private Boolean enabled;

    @Value("${ws.path}")
    private String path;

    @Value("${ws.allowedOrigins}")
    private String allowedOrigins;

    @Bean
    public WebSocketConfigurer webSocketConfigurer(HandshakeInterceptor handshakeInterceptor,
                                                   WebSocketHandler webSocketHandler) {
        // 如果WebSocket的路径为空，则设置默认路径为 "/websocket"
        if (StringUtils.isEmpty(this.getPath())) {
            this.setPath("/websocket");
        }
        // 如果允许跨域访问的地址为空，则设置为 "*"，表示允许所有来源的跨域请求
        if (StringUtils.isEmpty(this.getAllowedOrigins())) {
            this.setAllowedOrigins("*");
        }
        // 返回一个WebSocketConfigurer对象，用于配置WebSocket
        return registry -> registry
                // 添加WebSocket处理程序和拦截器到指定路径，设置允许的跨域来源
                .addHandler(webSocketHandler, this.getPath())
                //.addHandler(new AiTeacherWSHandler(), "/ws/chat")
                // 直接new没有进到spring的容器中，所以无法注入bean
                .addHandler(aiTeacherWSHandler(), "/ws/chat")
                .addInterceptors(handshakeInterceptor)
                .setHandshakeHandler(securityHandshakeHandler())
                .setAllowedOrigins(this.getAllowedOrigins());
    }

    @Bean
    public HandshakeInterceptor handshakeInterceptor() {
        return new PlusWebSocketInterceptor();
    }

    @Bean
    public WebSocketHandler webSocketHandler() {
        return new PlusWebSocketHandler();
    }

    @Bean
    public WebSocketHandler aiTeacherWSHandler() {
        return new AiTeacherWSHandler();
    }

    @Bean
    public DefaultHandshakeHandler securityHandshakeHandler() {
        return new SecurityHandshakeHandler();
    }
//    @Bean
//    public WebSocketTopicListener topicListener() {
//        return new WebSocketTopicListener();
//    }
}
